/**
 * @file 工单操作-算账
 * @author yangjiangming <449654337@qq.com>
 * @date 2018-12-10 20:13:16
 */
layui.define(['layer', 'form', 'NP', 'laytpl', 'table', 'zmnUtils', 'Vue', '$http'], function (exports) {
    let $ = layui.$;
    let form = layui.form;
    let table = layui.table;
    let NP = layui.NP;
    let opCommonUtils = layui.list_modify_common;
    let $http = layui.$http;
    let zmnUtils = layui.zmnUtils;
    let Vue = layui.Vue;

    let SAVE_ACCOUNT_URL = '/work/modify/save/account.action';
    let ERP_ACCOUNT_ENUM = {
        TRY: 2, // 预算张
    };

    let partDetail = accountVo.accountMasterPartVOList;//配件详细;
    let masterAccount = function () { //工程师算账;如果没有工程师提留金额 计算提留金额
        let arr = [];
        $.each(accountVo.accountMasterVOList, function (i, item) {
            // FICO 退款单工程师绩效基数=原单提留占比 * 退款单绩效基数，工程师提留=绩效基数+绩效基数补贴
            let rewardAmount = 0;
            let ficoRewardRate = 0;
            if (item.originalRewardAmount && item.originalBillAmount) {
                ficoRewardRate = NP.divide(item.originalRewardAmount || 0 , item.originalBillAmount || 0).toFixed(4);
                rewardAmount = NP.times(accountVo.billAmount || 0, ficoRewardRate);
            }
            item.rewardAmount = rewardAmount; // 退款单扣款
            item.billAmount = accountVo.billAmount; // 退款金额
            item.ficoRewardRate = ficoRewardRate || 0; // 原单提留占比

            //ERP 工程师扣款金额=（退款单绩效基数 * 原单提留占比 ）+额外增减项
            let erpBillAmount = 0;
            if (item.earningRate) {
                erpBillAmount = NP.times(accountVo.billAmount, item.earningRate);
            }
            item.erpEarning = erpBillAmount; // 工程师提留
            item.erpDeduction = erpBillAmount; // 工程提留结果
            item.otherFee = 0; // 额外增减项
            item.erpRewardRate = item.earningRate || 0; // 原单提留占比

            arr.push(item);
        });
        return arr;
    }();
    let spAccount = function () { //工程师算账;如果没有工程师提留金额 计算提留金额
        let arr = [];
        let item = accountVo.serviceProviderVO;

        if (!item) {
            return arr;
        }

        //ERP 工程师扣款金额=（退款单绩效基数 * 原单提留占比 ）+额外增减项
        let erpBillAmount = 0;
        if (item.earningRate) {
            erpBillAmount = NP.times(accountVo.billAmount, item.earningRate);
        }
        item.erpEarning = erpBillAmount;
        item.erpDeduction = erpBillAmount;
        item.otherFee = 0;
        item.erpRewardRate = item.earningRate || 0;

        arr.push(item);
        return arr;
    }();

    let colsPart = [[
        {field: 'masterName', title: '工程师'},
        {field: 'inSourcingAmount', title: '内采配件', templet: '#part-inSourcingAmount'},
        {field: 'outSourcingAmount', title: '外报配件', templet: "#part-outSourcingAmount"},
        {field: 'deliverAmount', title: '订单杂项费用', templet: '#part-deliverAmount'},
        {field: 'partAmount', title: '总计', templet: '#part-partAmount'},
    ]];
    let colsMasterAccount = [[
        {field: 'masterId', hide: true},
        {field: 'masterPhone', hide: true},
        {field: 'masterTypeName', hide: true},
        {field: 'originalBillAmount', hide: true},
        {field: 'originalRewardAmount', hide: true},
        {field: 'ficoRewardRate', hide: true},
        {field: 'masterName', title: '工程师'},
        {field: 'billAmount', title: '工程师绩效基数', templet: "#billAmount"},
        {field: 'rewardAmount', title: '工程师扣款', templet: "#rewardAmount"},
    ]];
    let colsMasterAccountERP = [[
        {field: 'masterId', hide: true},
        {field: 'masterPhone', hide: true},
        {field: 'masterTypeName', hide: true},
        {field: 'erpRewardRate', hide: true},
        {field: 'masterName', title: '工程师'},
        {field: 'billAmount', hide: true},
        {field: 'otherFee', title: '额外增减项', templet: "#otherFee"},
        {field: 'erpEarning', title: '工程师扣款', templet: "#erpEarning", hide: true},
        {field: 'erpDeduction', title: '工程师扣款', templet: "#erpDeduction"},
    ]];
    let colsSPAccountERP = [[
        {field: 'manageCompanyId', hide: true},
        {field: 'masterTypeName', hide: true},
        {field: 'erpRewardRate', hide: true},
        {field: 'manageCompanyName', title: '服务商'},
        {field: 'otherFee', title: '额外增减项', templet: "#otherFee"},
        {field: 'erpEarning', title: '服务商扣款', templet: "#erpEarning", hide: true},
        {field: 'erpDeduction', title: '服务商扣款', templet: "#erpDeduction"},
    ]];

    let tips = function (ele, str, callback) {
        toast({
            title: str,
            icon: 2,
            time: 2000
        });
        $(ele).focus();
        $(ele).val('');
        if (typeof callback === 'function') {
            callback();
        }
        return false;
    };

    /**
     * 总的绩效基数金额(主工程师+从工程师)
     * @type {number}
     */
    let totalBill = function () {
        let sum = 0;
        $.each(masterAccount, function (i, item) {
            sum = NP.plus(item.billAmount, sum);
        });
        sum = NP.divide(sum, 100);
        return sum;
    }();

    /**
     * 工程师绩效基数补贴输入
     */
    function masterBillInput() {
        let reg = /^[+-]?\d*\.?\d{0,2}$/;
        let tempTips = function (that,val){
            if (val === "-" || val === "+") {
                val = 0;
            }
            if (!reg.test(val)) {
                tips(that, "请输入正确数字或最多两位小数");
                //计算工程师提留;
                return;
            }
            if (Number(val) < 0 || Number(val) > 10000) {
                tips(that, "金额范围 0~10000");
                return;
            }
            //主工程师绩效基数金额 = 现有工程师绩效基数金额基础金额 - 所有从工程师的绩效基数金额 + 主工程师绩效基数补贴
            let $targetTr =  $(that).parents('tr');
            let masterBill = getText($targetTr, 'input[name=billAmount]');
            let fillValue = NP.plus(NP.times(masterBill,100), NP.times(val, 100));
            $(that).parents('tr').find('input[name=rewardAmount]').val(zmnUtils.unit.fenToYuan(fillValue));
        };
        $(".masteramount").on('keyup', '.subsidyAmount', function (event) {
            let val = event.currentTarget.value;
            tempTips(this,val);
        });
        $(".masteramount").on('blur', '.subsidyAmount', function (event) {
            let val = event.currentTarget.value;
            tempTips(this,val);
        })
    }


    /**
     * 工程师绩效基数补贴输入
     */
    function masterErpBillInput() {
        let reg = /^[+-]?\d*\.?\d{0,2}$/;
        let tempTips = function (that,val){
            if (val === "-" || val === "+") {
                val = 0;
            }
            if (!reg.test(val)) {
                tips(that, "请输入正确数字或最多两位小数");
                //计算工程师提留;
                return;
            }
            if (Number(val) < -100000 || Number(val) > 100000) {
                tips(that, "金额范围 -100000 ~ 100000");
                return;
            }
            //主工程师绩效基数金额 = 现有工程师绩效基数金额基础金额 - 所有从工程师的绩效基数金额 + 主工程师绩效基数补贴
            let $targetTr =  $(that).parents('tr');
            let masterBill = getText($targetTr, 'input[name=erpEarning]');
            let fillValue = NP.plus(NP.times(masterBill,100), NP.times(val, 100));
            if (Number(fillValue) > 0 ) {
                tips(that, "退款单工程师提留需小于 0，请重新填写：额外增减项金额");
                return;
            }
            $(that).parents('tr').find('input[name=erpDeduction]').val(zmnUtils.unit.fenToYuan(fillValue));
        };
        $(".erpAccount").on('keyup', '.otherFee', function (event) {
            let val = event.currentTarget.value;
            tempTips(this,val);
        });
        $(".erpAccount").on('blur', '.otherFee', function (event) {
            let val = event.currentTarget.value;
            tempTips(this,val);
        })
    }


    /**
     * 获取某个元素下子元素的文本值
     * @param item
     * @param ele
     * @returns {jQuery}
     */
    function getText(item, ele) {
        return $(item).find(ele).text() || $(item).find(ele).val();
    }

    /**
     * 获取某个元素的文本值
     * @param item
     * @returns {jQuery}
     */
    function getEleText(item) {
        return $(item).text() || $(item).val();
    }

    /**
     * 获取工程师算账列表;
     */
    function getMasterAmountList() {
        let $tr = $('.masteramount tbody').find('tr');
        let arr = [];
        $tr.each(function (i, item) {
            // fico
            let temp = {
                masterId: getText(item, 'td[data-field=masterId]'),
                masterName: getText(item, 'td[data-field=masterName]'),
                masterPhone: getText(item, 'td[data-field=masterPhone]'),
                masterTypeName: getText(item, 'td[data-field=masterTypeName]'),
                billAmount: NP.times(getText(item, 'input[name=billAmount]') || 0, 100),
                bonusAmount: NP.times(getText(item, 'input[name=rewardAmount]') || 0, 100),
                originalBillAmount: getText(item, 'td[data-field=originalBillAmount]') || 0,//原单收入
                originalRewardAmount: getText(item, 'td[data-field=originalRewardAmount]'),//原单提成
                ficoRewardRate: NP.times(getText(item, 'td[data-field=ficoRewardRate]') || 0, 10000)//提留金额
            }

            //ERP
            if (!accountVo.serviceProviderVO) {
                let $erpTr = $('.erpAccount tbody').find('tr').get(i);
                temp.earning = NP.times(getText($erpTr, 'input[name=erpEarning]') || 0, 100);
                temp.otherFee = NP.times(getText($erpTr, 'input[name=otherFee]') || 0, 100);
                temp.erpRewardRate = NP.times(getText($erpTr, 'td[data-field=erpRewardRate]') || 0, 10000);
            }

            arr.push(temp);

        });
        return arr;
    }

    /**
     * 获取服务商算账信息;
     */
    function getSpAmountList() {
        let $tr = $('.erpAccount tbody').find('tr').get(0);
        // fico
        let temp = {
            manageCompanyId: getText($tr, 'td[data-field=manageCompanyId]'),
            manageCompanyName: getText($tr, 'td[data-field=manageCompanyName]'),
            erpRewardRate: NP.times(getText($tr, 'td[data-field=erpRewardRate]') || 0, 10000),
            otherFee: NP.times(getText($tr, 'input[name=otherFee]') || 0, 100),
            earning: NP.times(getText($tr, 'input[name=erpEarning]') || 0, 100)
        }

        return temp;
    }

    /**
     * 提示消息
     * @param str {string} 提示信息
     * @returns {*}
     */
    function toast(opt) {
        layer.msg(opt.title, {
            icon: opt.icon,
            time: opt.time || 1000,
        }, function () {
            if (opt.icon == 1) {
                opCommonUtils.goOperateHome();
                //    location.reload();
            }
        })
    };

    /**
     * 从工程师绩效基数补贴之和
     */
    function sum(ele) {
        let $ele = $(ele);
        let sum = 0;//配件总和
        $ele.each(function (i, item) {
            let a = Number($(item).val()) || 0;
            sum = NP.plus(sum, a)
        });
        return sum;
    }

    /**
     * 获取某个元素下子元素的文本值
     * @param item
     * @param ele
     * @returns {jQuery}
     */
    function getText(item, ele) {
        return $(item).find(ele).text() || $(item).find(ele).val();
    }


    function saveAccount (data, btn) {
        return $http.lockSave(SAVE_ACCOUNT_URL, data, btn);
    }

    function realErpAccount (data, btn) {
        var $btns = $(btn).parent().children();
        saveAccount(data, $btns).then(function (result) {
            zmnUtils.layui.toastSuccess('操作成功', function () {
                opCommonUtils.goOperateHome();
            });
        }, function (msg) {
			var reason = msg || '未知';
			zmnUtils.layui.toastError('算账失败，原因：' + reason);
        });
    }

    function initTags() {
        let ficoTagText = '';
        let erpTagText = '';
        masterAccount.forEach(function (item ,index) {
            let masterInfo = item.masterName + '(' + item.masterTypeName + ') 原单比例: ';
            ficoTagText += masterInfo + NP.times(item.ficoRewardRate, 100) + '%<br/>';
            erpTagText += masterInfo + NP.times(item.erpRewardRate, 100) + '%<br/>';
        });
        ficoTagText += "（工程师扣款=原单提留占比 * 退款单绩效基数，退款单绩效基数=退款金额)";
        if (accountVo.serviceProviderVO) {
            let spVO = accountVo.serviceProviderVO;
            let spInfo = spVO.manageCompanyName + '原单比例: ';
            erpTagText = spInfo + NP.times(spVO.erpRewardRate, 100) + '%<br/>'
            erpTagText += "（服务商扣款金额=（退款单绩效基数 * 原单提留占比 ）+额外增减项）";
        }

        $("#fico_tag").html(ficoTagText);
        $("#erp_tag").html(erpTagText);



    }

    /**
     * 初始化页面
     */
    function initPage() {
        //配件明细
        table.render({
            elem: '#partdetail-table',
            cols: colsPart,
            data: partDetail
        });
        //工程师算账 - 比例提留
        table.render({
            elem: '#masteraccount-table',
            cols: colsMasterAccount,
            data: masterAccount,
        });

        // 多师傅算账 - erp
        table.render({
            elem: '#erp-masteraccount',
            cols: colsMasterAccountERP,
            data: masterAccount,
        });

        // 服务商算账 - erp
        table.render({
            elem: '#erp-spaccount',
            cols: colsSPAccountERP,
            data: spAccount,
        });

        initTags();
    }



    /**
     * 初始化页面事件
     */
    function initEvent() {
        //工程师绩效基数补贴
        masterBillInput();
        //工程师ERP额外增减项
        masterErpBillInput();

        form.on('submit(confirm)', function (obj) {

            let masterAmountList = getMasterAmountList();
            let field = obj.field;
            let params = {
                orderId: field.orderId,
                workId: field.workId,
                operatorRemark: field.operatorRemark,
                accountMasterVOList: masterAmountList,
                partsAmount: accountVo.partAmount,
                billAmount: accountVo.billAmount
            };

            if (accountVo.serviceProviderVO) {
                params.zsAccountSpDIO = getSpAmountList()
            }

            console.log(params);

            realErpAccount(params, obj.elem);

            return false;
        });
    }

    // 程序入口
    function init() {

        // 初始化页面
        initPage();

        // 初始化事件
        initEvent();
    }


    // 初始化
    init();

    exports('oms_work_modify_refund_account');
});
